package cn.biplam.back.services.config;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.biplam.common.interfaces.ConfigServer;
import cn.biplam.common.struc.SysStruc;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;
import cn.biplam.common.wrapper.sqlresult.SqlResult;

/**
 * 系统配置服务器接口实现类
 * @author WangSong Mar 6, 2009 3:15:19 PM
 * @version 1.0
 */
public class ConfigServerImpl extends UnicastRemoteObject implements ConfigServer{
	
	private static final long serialVersionUID = -2871493385996263094L;
	private Lock mLock=new ReentrantLock();
	private int iCount=0;
	
	/**
	 * 构造方法
	 * @throws RemoteException
	 */
	public ConfigServerImpl() throws RemoteException {
		iCount++;
	}
	
	/**
	 * 从数据库配置表中取系统参数
	 * @return  KvMap<String,String>
	 * @throws RemoteException
	 */
	public KvMap<String,String> getConfigGroup() throws ErrorMessage {
		
		KvMap<String,String> kvConfig = new KvMap<String,String>();
		addCount();
		try{
			SqlResult sr = new ConfigData().getConfigAll();
			for(int i=0;i<sr.size();i++){
				kvConfig.put(sr.get(i,SysStruc.SysParam.Param_ID),sr.get(i,SysStruc.SysParam.Apply_Value));
			}	
		}catch(ErrorMessage e){
			throw e;
		}catch(Exception e){
			throw new ErrorMessage(e,"ConfigServer get ConfigGroup failed!");
		}finally{
			reduceCount();
		}
		return kvConfig;
	}
	
	public int getCount() throws RemoteException {
		return this.iCount;
	}

	private synchronized void addCount() {
		this.iCount++;
	}

	private synchronized void reduceCount() {
		this.iCount--;
	}

	public void lock() throws RemoteException {
		mLock.lock();
	}

	public boolean trylock() throws RemoteException {
		return mLock.tryLock();
	}

	public void unlock() {
		mLock.unlock();
	}

}
